/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package masterclient;

import Protocol.ClientObject;
import Protocol.ComProtocol;
import Protocol.ReturnObject;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

    /**
    * Deze klasse zorgt ervoor dat het maken en laden van backups mogelijk wordt..
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
public class BackupManagement extends JPanel {
    private File file;
    private String path;
    private Writer writer = null;
    private ComProtocol cp;
    private String result = "";
    private GUI g;
    
    
    public BackupManagement(){
        createDir();
        
        setLayout(null);
    }
    
    /**
    * indien geen backups folder bestaat, wordt deze aangemaakt.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public void createDir(){
        String location = System.getProperty("user.dir");
        String dirName = location + "\\backups";
        File directory = new File(dirName);
        if(!directory.exists()){
            directory.mkdir();
        }
        path = dirName;
    }
    
    /**
    * Verstuurd een Auth select query om de juiste gegevens uit de database te halen.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String makeQuery(String tableName){
        String query = "";
        ClientObject o = null;
        
        cp = new ComProtocol("localhost", 5555);
        if(tableName.equals("User")){
            o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getAuthSelectQuery(), "SELECT [Name], [Password], [isMaster] FROM [" + tableName + "] WHERE Name != \'System\'");
        } else if(tableName.equals("Query")) {
            o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getAuthSelectQuery(), "SELECT [Query], [Description], [isActive] FROM [" + tableName + "]");
        }
        cp.send(o);
        ReturnObject ro = (ReturnObject) cp.recieve(); 
        cp.close();        
        if(ro != null){
            if(ro.getMessage().equals("ok")){                
                query = verwerkReturnObject(ro, tableName);              
            }
        }else {
            System.out.println("Geen RO terug");
        }
        return query;
    }
    
    /**
    * Als de query correct is worden de ArrayLists verwerkt in de vorm van een insert query.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String verwerkReturnObject(ReturnObject ro, String tableName){
        int columnCounter = 0;
        int rowCounter = 0;
        /*
        if(tableName.equals("User")){
            result = "INSERT INTO [Auth].[dbo].[User]([Name], [Password], [isMaster]) VALUES";
        } else if (tableName.equals("Query")){
            result = "INSERT INTO [Auth].[dbo].[Query]([Query], [Description], [isActive]) VALUES";
        }
        */
        result = "INSERT INTO [Auth].[dbo].["+ tableName + "](";
        
        for(String s :ro.getKolommen()){
            
            result += "[" + s.toString() + "]";
            if(columnCounter < ro.getKolommen().size()-1){
                result += ", ";
            }
            if(columnCounter == ro.getKolommen().size()-1){
                result += ") VALUES";
            }
            columnCounter++;
        }
        for(ArrayList a:ro.getRijen()){
            //System.out.println(ro.getRijen().size());
            int valueCounter = 1;
            for(Object s : a){
                //System.out.println("Row: " + rowCounter + " | Value: " + valueCounter + " | Column: " + columnCounter);
                
                if(valueCounter == 1){
                    result += "(\'";
                }
                
                result += s.toString();
                
                if(valueCounter != columnCounter){
                    result += "\',\'";
                }
                if(valueCounter == columnCounter && rowCounter != ro.getRijen().size()-1){
                    result += "\'),";
                }
                if(valueCounter == columnCounter && rowCounter == ro.getRijen().size()-1){
                    result += "\');";
                }
                if(valueCounter == columnCounter){
                    rowCounter++;
                }
                valueCounter++;
            }
        }
        System.out.println(result);
        return result;
    }
    
    /**
    * Deze functie voert de aangemaakte inser query uit.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public void executeQuery(String executableQuery){
        cp = new ComProtocol("localhost", 5555);
        ClientObject o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getUpdateQuery(), executableQuery);
        cp.send(o);
        ReturnObject ro = (ReturnObject) cp.recieve(); 
        cp.close();        
        if(ro != null){
            if(ro.getMessage().equals("ok")){                
                System.out.println("Query uitgevoerd.");
            }
        }else{
            System.out.println("Geen RO terug");
        }  
    }
    
    /**
    * Maakt een nieuw bestand aan met de huidige datum en tijd en zet daar de aangemaakte insert query in.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    public void createBackup(){
        file = new File(path, getFileName());
        if(!file.exists()){
            try{
                file.createNewFile();
                BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
                bw.write(makeQuery("User"));
                bw.write("\r\n");
                bw.write(makeQuery("Query"));
                bw.close();
                JOptionPane.showMessageDialog(this, "A backup has been created.");
            }
            catch(IOException e){
                System.out.println(e.getMessage());
            }
        } else{
            System.out.println("File already exists");
        }
    }
    
    /**
    * Leest een bestand in en voert deze uit met behulp van de executeQuery() functie.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public void loadBackup(String file){
        BufferedReader br = null;
        String line = "";
        String total = "";
        int firstLetter = 0;
        int lastLetter = 0;
        int lineNumber = 0;
        try {
            br = new BufferedReader(new FileReader(file));
            while((line = br.readLine()) != null){
                total += line + "\n";
            }
            br.close();
        } catch (FileNotFoundException ex) {
            System.out.println("Bestand niet gevonden.");
        } catch (IOException ex){
            System.out.println("IO Exception");
        }
        
        executeQuery("DELETE FROM [User] WHERE Name != \'System\'");
        executeQuery("DELETE FROM [Query]");
        for(int i = 0;i<total.length();i++){
            if(total.substring(i, i+1).equals("\n")){
                lastLetter = i;
                if(lineNumber == 0){
                    String queryA = total.substring(firstLetter, lastLetter);
                    executeQuery(queryA);
                } if(lineNumber == 1) {
                    String queryB = total.substring(firstLetter, lastLetter);
                    executeQuery(queryB);
                }
                firstLetter = i+1;
                lineNumber++;
            }
        }
    }
    
    /**
    * Haalt de huidige datum op.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String getDate(){
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        Date date = new Date();
        return dateFormat.format(date);
    }
    
    /**
    * Haalt het huidige uur op.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String getHour(){
        DateFormat dateFormat = new SimpleDateFormat("HH");
        Date date = new Date();
        return dateFormat.format(date);
    }
    
    /**
    * Haalt het huidig aantal minuten op.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String getMinute(){
        DateFormat dateFormat = new SimpleDateFormat("mm");
        Date date = new Date();
        return dateFormat.format(date);
    }
    
    /**
    * Haalt het huidig aantal seconden op.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String getSecond(){
        DateFormat dateFormat = new SimpleDateFormat("ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
    
    /**
    * Verwerkt de datumgegevens naar een String.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String getFileName(){ //mag geen / bevatten dit zorgt voor errors, ook geen tekens die niet ondersteurnt worden door windows
        return "Backup " + getDate() + " " + getHour() + "u" + getMinute() + "m" + getSecond() + "s.back";
    }
    
    /**
    * Geeft de locatie van de backups folder terug.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String getPath(){
        return path;
    }
}
